<template>
  <div>
    <!-- 面包屑导航区域 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>{{ menuTitle.main }}</el-breadcrumb-item>
      <el-breadcrumb-item>{{ menuTitle.item }}</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.condition" clearable @clear="getGoodsList">
            <el-button slot="append" icon="el-icon-search" @click="getGoodsList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="goAddpage"> 添加商品 </el-button>
        </el-col>
      </el-row>

      <!-- table 表格区 -->
      <el-table :data="goodsList" border>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="商品名称" prop="goodName"></el-table-column>
        <el-table-column label="商品价格(元)" prop="price" width="95px"></el-table-column>
        <el-table-column label="商品重量(g)" prop="weight" width="90px"></el-table-column>
        <el-table-column label="商品数量" prop="number" width="70px"></el-table-column>
        <el-table-column label="创建时间" width="140px">
          <template slot-scope="scope">
            {{ scope.row.addTime | dateFormat }}
          </template>
        </el-table-column>
        <el-table-column label="操作" width="130px">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-tooltip effect="dark" content="编辑商品信息" placement="top-start" :enterable="false">
              <el-button type="primary" icon="el-icon-edit" size="mini" @click="showEditDialog(scope.row.id)"></el-button>
            </el-tooltip>
            <!-- 删除按钮 -->
            <el-tooltip effect="dark" content="删除商品信息" placement="top-start" :enterable="false">
              <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteById(scope.row.id)"> </el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.currentPage"
        :page-sizes="[5, 10, 20, 30]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        background
      >
      </el-pagination>
    </el-card>

    <!-- 修改用户信息对话框 -->
    <el-dialog title="修改商品信息" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed" :close-on-click-modal="false">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <!-- 商品名称 -->
        <el-form-item label="商品名称" prop="goodName">
          <el-input v-model="editForm.goodName" type="textarea"></el-input>
        </el-form-item>
        <!-- 商品重量 -->
        <el-form-item label="商品重量" prop="weight">
          <el-input v-model="editForm.weight"></el-input>
        </el-form-item>
        <!-- 商品数量 -->
        <el-form-item label="商品数量" prop="number">
          <el-input v-model="editForm.number" type="number"></el-input>
        </el-form-item>
        <!-- 商品价格 -->
        <el-form-item label="商品价格" prop="price">
          <el-input v-model="editForm.price"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editGood">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    const checkPrice = (rule, value, cb) => {
      const regPrice = /^[0-9]{1,}\.[0-9]{2}/
      return regPrice.test(value) ? cb() : cb(new Error('请输入合法的价格, xx.00'))
    }

    return {
      // 面包屑导航标题
      menuTitle: {
        main: '',
        item: ''
      },
      // 查询条件
      queryInfo: {
        condition: '',
        currentPage: 1,
        pageSize: 10
      },
      // 商品总数
      total: 0,
      // 商品列表
      goodsList: [],
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        goodName: [{ required: true, message: '请输入商品名称', trigger: 'blur' }],
        weight: [{ required: true, message: '请输入商品重量', trigger: 'blur' }],
        number: [{ required: true, message: '请输入商品数量', trigger: 'blur' }],
        price: [
          { required: true, message: '请输入商品价格', trigger: 'blur' },
          { validator: checkPrice, trigger: 'blur' }
        ]
      }
    }
  },
  created() {
    this.getMenuList()
    this.getGoodsList()
  },
  methods: {
    // 获取面包屑导航标题
    async getMenuList() {
      const { data: res } = await this.$axios.get('/menu/getMenuList.do')
      if (!res.flag) return this.$message.error(res.message)
      // 获取当前激活路径
      const activePath = window.sessionStorage.getItem('activePath')
      // 循环判断激活路径对应的路径名称
      res.data.forEach(value => {
        value.menuItem.forEach(item => {
          if (item.path === activePath) {
            this.menuTitle.item = item.title
            this.menuTitle.main = value.title
          }
        })
      })
    },
    // 获取商品列表
    async getGoodsList() {
      const { data: res } = await this.$axios.post('/goods/getGoodsList.do', this.queryInfo)
      if (res === null) return this.$message.error('获取商品列表失败')
      this.total = res.total
      this.goodsList = res.rows
    },
    // 处理当前页发生变化
    handleCurrentChange(newPage) {
      this.queryInfo.currentPage = newPage
      this.getGoodsList()
    },
    // 处理每页条数发生变化
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize
      this.getGoodsList()
    },
    // 跳转到添加商品页面
    goAddpage() {
      this.$router.push('/add')
    },
    // 删除商品
    async deleteById(id) {
      // 防止用户误操作
      const result = await this.$confirm('此操作将永久删除该商品, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(e => e)

      if (result !== 'confirm') return this.$message.info('已经取消删除')

      // 向后台发起请求, 删除指定 id 的用户
      const { data: res } = await this.$axios.delete(`/goods/delete.do?id=${id}`)
      if (!res.flag) return this.$message.error(res.message)

      this.$message.success(res.message)
      this.getGoodsList()
    },
    // 展示编辑商品基本信息对话框
    async showEditDialog(id) {
      this.editDialogVisible = true
      const { data: res } = await this.$axios.get(`/goods/getGoodById.do?id=${id}`)
      if (!res.flag) return this.$message.error(res.message)
      this.editForm = res.data
    },
    // 编辑商品信息对话框的关闭
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 编辑商品
    editGood() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) return false

        const { data: res } = await this.$axios.put('/goods/edit.do', this.editForm)
        if (!res.flag) return this.$message.error(res.message)

        this.$message.success(res.message)
        this.editDialogVisible = false
        this.getGoodsList()
      })
    }
  }
}
</script>
